import { createSlice } from '@reduxjs/toolkit'
import axios from 'axios'

const foodsStore = createSlice({
    name: 'foods',
    initialState: {
        foods: [],
        activeIndex:0,
        cards:[]
    },
    reducers:{
        setFoods(state, action){
            state.foods = action.payload
        },
        setActiveIndex(state, action){
            state.activeIndex = action.payload
        },
        setCards(state, action){
            const item = state.cards.find(item => item.id === action.payload.id)
            if(item){
                item.count ++
            }else{
                state.cards.push(action.payload)
            }
        },
        addNum(state, action){
            const item = state.cards.find(item => item.id === action.payload.id)
            if(item){
                item.count ++
            }
        },
        minusNum(state, action){
            const item = state.cards.find(item => item.id === action.payload.id)
            if(item.count === 1){
                return
            }
            item.count --
        },
        deleteCard(state, action){
            const items = state.cards.filter(item => item.id !== action.payload.id)
            state.cards = items
      
        },
        /**清除购物车 */
        clearCart(state){
            state.cards = []
        }
    }
})

const { setFoods, setActiveIndex,setCards,deleteCard,addNum,minusNum,clearCart} = foodsStore.actions

const fetchFood= () =>{
    return async (dispatch) => {
        const response = await axios.get('http://localhost:8080/s4/foods/queryFoods')
        dispatch(setFoods(response.data))
    }
}

export { fetchFood ,setActiveIndex,setCards,deleteCard,addNum,minusNum,clearCart}

const reducer = foodsStore.reducer

export default reducer
